import cv2
import numpy as np


def detect_glove_direction(image, left_template, right_template):
    # 对图像和模板进行边缘检测预处理
    image_edges = cv2.Canny(image, 50, 150)
    left_template_edges = cv2.Canny(left_template, 50, 150)
    right_template_edges = cv2.Canny(right_template, 50, 150)

    # 进行模板匹配
    result_left = cv2.matchTemplate(image_edges, left_template_edges, cv2.TM_CCOEFF_NORMED)
    result_right = cv2.matchTemplate(image_edges, right_template_edges, cv2.TM_CCOEFF_NORMED)

    # 获取匹配结果的最大值
    min_val_left, max_val_left, min_loc_left, max_loc_left = cv2.minMaxLoc(result_left)
    min_val_right, max_val_right, min_loc_right, max_loc_right = cv2.minMaxLoc(result_right)

    # 根据匹配得分判断手指方向
    if max_val_left > max_val_right:
        return "Left"
    else:
        return "Right"


# 读取左右模板图像
left_template_path = 't_left1.jpg'
right_template_path = 't_right1.jpg'
left_template = cv2.imread(left_template_path, cv2.IMREAD_GRAYSCALE)
right_template = cv2.imread(right_template_path, cv2.IMREAD_GRAYSCALE)

# 打开摄像头
cap = cv2.VideoCapture(0)
count = 0
while True:
    # 读取一帧画面
    ret, frame = cap.read()
    if not ret:
        break

    # 将画面转换为灰度图像
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 调用 detect_glove_direction 函数
    direction = detect_glove_direction(gray_frame, left_template, right_template)
    print("direction:", direction) 

    # 在画面上显示手指方向
    cv2.putText(frame, f"Direction: {direction}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    # 显示画面
    cv2.imshow('Glove Direction Detection', frame)

    # 按 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
    